import { Injectable } from '@angular/core'
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { Observable, of } from 'rxjs'
import { StoreDetailComponent } from 'app/routes/store/detail/detail.component'
import { DataService } from '@shared/services/data.service'

@Injectable()
export class StoreDetailRouterGuardClass implements CanDeactivate<StoreDetailComponent> {
  targetUrlArrReg = [new RegExp(/\/biz\/stores\/\w*\/qr\/channel/)]

  constructor(private dataService: DataService) {}

  canDeactivate(
    component: StoreDetailComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot,
  ): Observable<boolean> {
    const { url } = nextState
    const isTargetUrl = this.checkIsTargetUrl(url)
    if (!isTargetUrl) {
      this.dataService.resetToken()
    }
    return of(true)
  }

  private checkIsTargetUrl(url: string): boolean {
    const head = url.split('?')[0]
    let isTarget = false

    this.targetUrlArrReg.forEach(reg => {
      if (reg.test(head)) {
        isTarget = true
      }
    })
    return isTarget
  }
}
